package cn.mumzone.pos.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.base.BaseActivity;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.basic.util.ToastUtil;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.R;
import cn.mumzone.pos.event.UpdateReserveTimeEvent;
import cn.mumzone.pos.model.ReserveOrderEntity;
import cn.mumzone.pos.model.ReserveTimeEntity;
import cn.mumzone.pos.presenter.ReserveWeekEntity;
import cn.mumzone.pos.presenter.UpdateReserveTimePresenter;
import cn.mumzone.pos.presenter.contract.UpdateReserveTimeContract;
import cn.mumzone.pos.ui.adapter.ADA_ReserveTime;
import cn.mumzone.pos.ui.adapter.ADA_ReserveWeek;
import cn.mumzone.pos.ui.widgets.others.FullyGridLayoutManager;

/**
 * Created by qiuzhenhuan on 2019/7/6.
 */

public class ACT_UpdateReserveTime extends BaseActivity<UpdateReserveTimePresenter> implements UpdateReserveTimeContract.View {

    private static final String KEY_RESERVE = "reserve";

    private ReserveOrderEntity mReserveEntity;

    @BindView(R.id.rv_weeks)
    RecyclerView rvWeeks;
    @BindView(R.id.rv_morning)
    RecyclerView rvMorning;
    @BindView(R.id.rv_afternoon)
    RecyclerView rvAfternoon;
    @BindView(R.id.ll_time)
    LinearLayout llTime;
    @BindView(R.id.fl_morning)
    FrameLayout flMorning;
    @BindView(R.id.tv_morning_empty)
    TextView tvMorningEmpty;
    @BindView(R.id.fl_afternoon)
    FrameLayout flAfternoon;
    @BindView(R.id.tv_afternoon_empty)
    TextView tvAfternoonEmpty;

    private ADA_ReserveTime mMorningAdapter;
    private ADA_ReserveTime mAfternoonAdapter;
    private ADA_ReserveWeek mWeekAdapter;
    private String selectTime;


    @Override
    protected void getBundleExtras(Bundle extras) {
        mReserveEntity = (ReserveOrderEntity) extras.get(KEY_RESERVE);

        if (mReserveEntity == null) {
            ToastUtil.makeText(this, "预约数据有误", false);
            return;
        }
    }

    @Override
    protected void initEventAndData() {

        initDateTime();

        String startTime;
        //预约时间为当天或当天以前，从当前时间开始查询技师可用时间
        if (AppDateUtil.compareDateIsLessThanNow(mReserveEntity.getAppointmentTime())
                || AppDateUtil.isSameDay(AppDateUtil.timeStamp2Date(mReserveEntity.getAppointmentTime()), new Date())) {
            startTime = String.valueOf(System.currentTimeMillis());
        } else {
            startTime = mReserveEntity.getAppointmentTime();
        }
        selectTime = startTime;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.loadAvailableTime(mReserveEntity.getId(), selectTime);
    }

    private void initDateTime() {
        rvWeeks.setLayoutManager(new FullyGridLayoutManager(mContext, 7));
        mWeekAdapter = new ADA_ReserveWeek(mContext);
        rvWeeks.setAdapter(mWeekAdapter);
        mWeekAdapter.update(getNextWeekDate(), true);
        long appointmentTime = Long.valueOf(mReserveEntity.getAppointmentTime());
        mWeekAdapter.setSelectedDate(AppDateUtil.getTimeStamp(appointmentTime, AppDateUtil.MM_DD2));
        mWeekAdapter.setOnItemSelectedListener(new ADA_ReserveWeek.OnItemSelectedListener() {
            @Override
            public void onItemSelected(ReserveWeekEntity entity) {
                mMorningAdapter.clearCheckStatus();
                mAfternoonAdapter.clearCheckStatus();
                mMorningAdapter.setPreSelectedDay(entity.getFullDate());
                mAfternoonAdapter.setPreSelectedDay(entity.getFullDate());
                selectTime = entity.getFullDate();
                mPresenter.loadAvailableTime(mReserveEntity.getId(), selectTime);
            }
        });

        rvMorning.setLayoutManager(new FullyGridLayoutManager(mContext, 7));
        mMorningAdapter = new ADA_ReserveTime(mContext);
        rvMorning.setAdapter(mMorningAdapter);
        mMorningAdapter.setPreSelectedDay(StringUtils.get(mReserveEntity.getAppointmentTime()));
        mMorningAdapter.setDefaultSelectTime(StringUtils.get(mReserveEntity.getAppointmentTime()));
        mMorningAdapter.setOnItemSelectedListener(new ADA_ReserveTime.OnItemSelectedListener() {
            @Override
            public void onItemSelected(View view) {
                mAfternoonAdapter.clearCheckStatus();
            }
        });

        rvAfternoon.setLayoutManager(new FullyGridLayoutManager(mContext, 7));
        mAfternoonAdapter = new ADA_ReserveTime(mContext);
        rvAfternoon.setAdapter(mAfternoonAdapter);
        mAfternoonAdapter.setPreSelectedDay(StringUtils.get(mReserveEntity.getAppointmentTime()));
        mAfternoonAdapter.setDefaultSelectTime(StringUtils.get(mReserveEntity.getAppointmentTime()));
        mAfternoonAdapter.setOnItemSelectedListener(new ADA_ReserveTime.OnItemSelectedListener() {
            @Override
            public void onItemSelected(View view) {
                mMorningAdapter.clearCheckStatus();
            }
        });

    }

    @OnClick({R.id.iv_back, R.id.btn_cancel, R.id.btn_confirm,R.id.tv_schedule})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
            case R.id.btn_cancel:
                finish();
                break;
            case R.id.btn_confirm:

                String munute = "";
                if (mMorningAdapter.getSelectedTime() != null) {
                    munute = mMorningAdapter.getSelectedTime().getMinuteName();
                } else if (mAfternoonAdapter.getSelectedTime() != null) {
                    munute = mAfternoonAdapter.getSelectedTime().getMinuteName();
                }

                if (mWeekAdapter.getSelectedWeek() == null) {
                    showError("请选择日期");
                    return;
                }

                if (StringUtils.isEmpty(munute)) {
                    showError("请选择时间");
                    return;
                }

                String selectDateTime = String.format("%s %s", AppDateUtil.getDateToString(
                        Long.valueOf(mWeekAdapter.getSelectedWeek().getFullDate()), AppDateUtil.YYYY_MM_DD), munute);

                mPresenter.doUpdateReserveTime(mReserveEntity.getId(), AppDateUtil.date2TimeStamp(selectDateTime, AppDateUtil.YYYY_MM_DD_HH_MM));
                break;
            case R.id.tv_schedule:
                if(AppConstants.TEMP_USER_PERMISSION !=null && AppConstants.TEMP_USER_PERMISSION.isScheduling()){
                    ACT_Schedule.startAc(mContext);
                }else {
                    PosToast.INSTANCE.makeShortToast(mContext,"无排班权限");
                }
                break;
        }
    }

    public List<ReserveWeekEntity> getNextWeekDate() {
        ArrayList<ReserveWeekEntity> arrayList = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            // 时间增加
            long currentTime = System.currentTimeMillis() + i * 24 * 60 * 60 * 1000;

            ReserveWeekEntity weekEntity = new ReserveWeekEntity();

            // 设置日期
            weekEntity.setDate(AppDateUtil.getTimeStamp(currentTime, AppDateUtil.MM_DD2));
//            weekEntity.setFullDate(AppDateUtil.getTimeStamp(currentTime, AppDateUtil.YYYY_MM_DD));
            weekEntity.setFullDate(StringUtils.getString(currentTime));

            // 设置星期
            switch (i) {
                case 0:
                    weekEntity.setWeek("今天");
                    break;
                case 1:
                    weekEntity.setWeek("明天");
                    break;
                default:
                    weekEntity.setWeek(AppDateUtil.getWeekOfDate(currentTime));
            }

            // 添加到集合
            arrayList.add(weekEntity);

        }
        return arrayList;
    }

    @Override
    public void showAvailableTime(ArrayList<ReserveTimeEntity> morning, List<ReserveTimeEntity> afternoon) {
        if (ListUtil.isListEmpty(morning) && ListUtil.isListEmpty(afternoon)) {
            toggleShowEmpty(true, R.drawable.svg_ic_empty_server, "您还没有排班哦~",
                    "立即排班", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if(AppConstants.TEMP_USER_PERMISSION !=null && AppConstants.TEMP_USER_PERMISSION.isScheduling()){
                                ACT_Schedule.startAc(mContext);
                            }else {
                                PosToast.INSTANCE.makeShortToast(mContext,"无排班权限");
                            }
                        }
                    });
        } else {
            toggleCloseEmpty();
            tvMorningEmpty.setVisibility(ListUtil.isListEmpty(morning) ? View.VISIBLE : View.GONE);
            tvAfternoonEmpty.setVisibility(ListUtil.isListEmpty(afternoon) ? View.VISIBLE : View.GONE);
            rvMorning.setVisibility(ListUtil.isListEmpty(morning) ? View.GONE : View.VISIBLE);
            rvAfternoon.setVisibility(ListUtil.isListEmpty(afternoon) ? View.GONE : View.VISIBLE);
        }
        mMorningAdapter.update(morning, true);
        mAfternoonAdapter.update(afternoon, true);

        mMorningAdapter.setDefaultSelectTime(StringUtils.get(mReserveEntity.getAppointmentTime()));
        mAfternoonAdapter.setDefaultSelectTime(StringUtils.get(mReserveEntity.getAppointmentTime()));
    }

    @Override
    protected View getTargetView() {
        return llTime;
    }

    @Override
    public void showUpdateReserveTimeSuccess(String date) {
        ToastUtil.makeText(this, "修改成功", false);
        RxBus.getDefault().post(new UpdateReserveTimeEvent(date));
        finish();
    }

    @Override
    protected int getLayout() {
        return R.layout.act_update_reserve_time;
    }

    public static void startAc(Context context, ReserveOrderEntity reserveOrderEntity) {
        Intent intent = new Intent(context, ACT_UpdateReserveTime.class);
        intent.putExtra(KEY_RESERVE, reserveOrderEntity);
        context.startActivity(intent);
    }
}
